package com.by.task;


import com.by.bean.Order;
import com.by.bean.OrderDetail;
import com.by.config.RedisUtils;
import com.by.mapper.OrderDetailMapper;
import com.by.service.OrderService;
import com.by.service.impl.OrderType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class GenerateOrder extends Thread{

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    OrderService orderService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @PostConstruct //相当于spring bean中的init方法 bean实例化后执行 且执行一次
    public void init(){
        this.start(); // 启动线程
    }

    @Override
    public void run(){
        log.info("------开始获取订单队列中的消息 用于生成订单------");
        while (true){
            //从队列中获取订单信息
            String msg = redisUtils.rpop(Constant.ORDER_QUEUE);
            if(null == msg){
                //说明队列没有 等待
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }else {
                //队列中有 msg=userId:id
                String[] gdt = msg.split(":");
                int userId = Integer.parseInt(gdt[0]);
                int goodId = Integer.parseInt(gdt[1]);
                //生成订单(商品信息:1.从redis取 2.生成订单时 从数据库查)
                //获取订单及明细相关数据 生成订单
                //调用生成订单的业务逻辑
                //取商品信息
                int num = 1;
                String name = redisUtils.get("goods:"+goodId+":name");
                double price = Double.parseDouble(redisUtils.get("goods:"+goodId+":price"));
                //定义订单
                Order order = new Order();
                order.setPayable(price);
                order.setMoney(price);
                order.setUserId(userId);
                order.setType(OrderType.SECOND_KILL);

                //定义订单明细
                OrderDetail detail = new OrderDetail();
                detail.setNum(num);
                detail.setPrice(price);
                detail.setName(name);
                detail.setGoodsId(goodId);
                List<OrderDetail> list = new ArrayList<>();
                list.add(detail);
                order.setOrderDetails(list);
                int rs = orderService.save(order);
                if (rs==0){
                    log.error("用户["+userId+"]抢购商品["+goodId+"]生成订单失败");
                } else if (rs>0) {
                    //将id记录到redis中 同时设置过期时间
                    redisUtils.set("order:id:"+rs,rs+"",10);
                }

            }
        }
    }
}
